# coding:utf-8
# FILENAME: PySimpleGUI + 爬虫获取天气
# USING_DATABASE: NONE
# LICENSE: The MIT License (MIT) Copyright © 2020 Feihu233
# DESCRIPTION: README.md

import PySimpleGUI, requests, json, pyperclip, sys

# 获取字典 {城市代码:城市名} - OK
def get_city_dicts(city_dicts=dict()):
    city_dicts=dict()
    # 字典: {城市代码:城市名}
    with open('./docs/城市代码.txt', mode="r", encoding="utf-8") as data:
        for lines in data.readlines():
            if lines.isspace():
                continue
            city_dicts[lines[:9]] = lines[10:].strip()
    return city_dicts
# 提前建立这一段代码, 以处理函数默认值问题
city_dicts = get_city_dicts()

# 输入城市名或城市代号
def get_data(city, dicts=city_dicts, result=dict()):
    city_name = list(dicts.values())
    if str(city) in dicts: # NUM
        url = 'http://wthrcdn.etouch.cn/weather_mini?citykey=%s' % str(city)
    elif str(city) in city_name: # TEXT
        url = 'http://wthrcdn.etouch.cn/weather_mini?city=%s' % str(city)
    else:
        return "输入错误, 为空或非法输入!"
    result = json.loads(requests.get(url).text)["data"]
    return result

# 获得温度
def get_temp(temp_max, temp_min, result=''):
    temp_max, temp_min = list(temp_max), list(temp_min)
    del temp_max[0:3], temp_min[0:3]
    result = ''.join(temp_max) + ' -' + ''.join(temp_min)
    return result

'''
窗口设计

输入城市名/ID: [        Input        ]
选择时间:      [ 选择框 ]
[提交 Button] [复制到剪贴板 Button]
温度: [] 天气: [] 风向: []
'''
layout = [
    [
        PySimpleGUI.Text('输入城市名/ID: ', size=(11,1)),
        PySimpleGUI.Input(key="-ID-", size=(12, 1)),
        PySimpleGUI.Text('选择时间: ', size=(7, 1)),
        PySimpleGUI.Combo(
            ("昨天", "今天", "明天", "两天后", "三天后", "四天后"),
            default_value="明天",
            key="-Day-",
            size = (6,1)
        ),
        PySimpleGUI.Button("提交", key="-Submit-", size=(4, 1)),
    ],
    [
        PySimpleGUI.Output(size=(51,7), key='-OUTPUT-')
    ]
]

PySimpleGUI.theme('DarkAmber') # 设置窗口主题
windows = PySimpleGUI.Window("天气预报小程序", layout)  # 创建窗口
# 有些时候 while 当中直接运行此代码会出错, 若出错则启用这段垫材
#if windows.read():
#    event, value = windows.read()
CopyAlert = '已复制到剪贴板'
TimeList = {'今天': 0, '明天': 1, '两天后': 2, '三天后': 3, '四天后': 4,}

while True:
    # 需要点击的控件列表, 需要输入的控件列表
    event, value = windows.read()
    # 点 x 时获取的 event 为 NULL, 用来处理推出
    if event is None: windows.close(); break
    # 主判断, 最大代码量用于处理日期
    if (event == '-Submit-') and (value['-ID-'] in city_dicts.keys() or value['-ID-'] in city_dicts.values()):
        data = get_data(value['-ID-'], city_dicts)
        if value['-Day-'] == '昨天':
            # Temp, Weather, Wind
            result = data['city'] + value['-Day-'] + '的天气'
            result += "\n温度: " + get_temp(data["yesterday"]["low"], data["yesterday"]["high"])
            result += "\n天气: " + data["yesterday"]["type"]
            result += "\n风向: " + data["yesterday"]["fx"]
            results = '\n' + result+CopyAlert+'\n'
            print(results);  pyperclip.copy(result)
            pass
        elif value['-Day-'] in TimeList:
            use_data = data["forecast"][TimeList[value['-Day-']]]
            result = data['city'] + value['-Day-'] + '的天气'
            result += "\n温度: " + get_temp(use_data["low"], use_data["high"])
            result += "\n天气: " + use_data["type"]
            result += "\n风向: " + use_data["fengxiang"] + '\n'
            results = result + CopyAlert + '\n'
            print(results); pyperclip.copy(result)
    else:
        print("请检查输入!")
